package tt.dz.dao.ext.charger;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import tt.dz.dao.base.OmsCommonDao;
import tt.dz.entity.charger.OmsChargerRate;
import tt.dz.entity.exception.OmsDaoException;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 电桩费率数据操作Dao
 * @author xielongfei
 *
 */
@Repository
public class OmsChargerRateDao extends OmsCommonDao<OmsChargerRate> 
{
	public Integer findMaxRateSchema() throws OmsDaoException
	{
		try
		{
			String sql = "select max(rate_schema) from oms_charger_rate";
			Integer result = (Integer) this.getJdbcTemplate().queryForObject(sql, Integer.class);
			return result == null ? 0:result;
		}
		catch(Exception e)
		{
			throw new OmsDaoException(e);
		}
	}
	
	public Integer findMaxSerialNoByRateSchema(Integer rateSchema) throws OmsDaoException
	{
		try
		{
			String sql = "select max(serial_no) from oms_charger_rate where rate_schema = ?";
			Object[] args = {rateSchema};
			Integer result = this.getJdbcTemplate().queryForInt(sql,args);
			return result == null ? 0:result;
		}
		catch(Exception e)
		{
			throw new OmsDaoException(e);
		}
	}
	
	public void deleteChargerRatesByRateSchema(Integer rateSchema) throws OmsDaoException
	{
		try
		{
			String sql = "delete from oms_charger_rate where rate_schema = ?";
			Object[] args = {rateSchema};
			this.getJdbcTemplate().update(sql, args);
		}
		catch(Exception e)
		{
			throw new OmsDaoException(e);
		}
	}
	
	public void batchAddChargerRatesByRateSchema(final List<OmsChargerRate> chargerRates,final Integer rateSchema)throws OmsDaoException
	{
		try
		{
			String batchSql = "INSERT INTO `oms_charger_rate`(rate_schema,serial_no,start_time,end_time,rate,valid_flag,oper_id,set_time,fee_type,charge_mode) VALUES (?,?, ?, ?, ?, 1, ?,now(),?,?)";
			this.getJdbcTemplate().batchUpdate(batchSql, new BatchPreparedStatementSetter() 
			{
				@Override
				public void setValues(PreparedStatement arg0, int arg1) throws SQLException 
				{
					OmsChargerRate ocr = chargerRates.get(arg1);
					int index = 1;
					arg0.setInt(index++, rateSchema);
					arg0.setInt(index++, index);
					arg0.setTime(index++, ocr.getStart_time());
					arg0.setTime(index++, ocr.getEnd_time());
					arg0.setBigDecimal(index++, ocr.getRate());
					arg0.setString(index++, ocr.getOper_id());
					arg0.setInt(index++, ocr.getFee_type());
					arg0.setInt(index, ocr.getCharge_mode());
				}
				
				@Override
				public int getBatchSize() {
					return chargerRates.size();
				}
			});
		}
		catch(Exception e)
		{
			throw new OmsDaoException(e);
		}
	}
}
 